package com.server.modules.sys.utils;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {
	private static final int NEGATIVE_ONE = -1;
	/**
     * 使用md5的算法进行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
     
    /** 
     * Get MD5 of one file:hex string,test OK! 
     *  
     * @param file 
     * @return 
     */  
    public static String getFileMD5(File file) {  
        if (!file.exists() || !file.isFile()) {  
            return null;  
        }  
        MessageDigest digest = null;  
        FileInputStream in = null;  
        byte buffer[] = new byte[1024];  
        int len;  
        try {  
            digest = MessageDigest.getInstance("MD5");  
            in = new FileInputStream(file);  
            while ((len = in.read(buffer, 0, 1024)) != NEGATIVE_ONE) {  
                digest.update(buffer, 0, len);  
            }  
            in.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        BigInteger bigInt = new BigInteger(1, digest.digest());  
        return bigInt.toString(16);  
    }  
  
    /*** 
     * Get MD5 of one file！test ok! 
     *  
     * @param filepath 
     * @return 
     */  
    public static String getFileMD5(String filepath) {  
        File file = new File(filepath);  
        return getFileMD5(file);  
    }  
    public static void main(String[] args) {
         
        System.out.println(md5("123"));
    }
    
    

}
